import { useEffect } from 'react';
import { Space, Button } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { useTRState, TjSelect } from '@/pages/ETrade/components';

const getDateRange = () => {
  return [moment().add(-1, 'months'), moment()];
};

export default ({ power, onChange = () => {}, refresh }) => {
  const [state, setState] = useTRState({
    // 表单
    regionItem: null,
    stationIdList: [],
    dates: getDateRange(),
  });

  useEffect(() => {
    power?.[0] && onChangeRegion(power[0], 'search');
  }, [power]);

  useEffect(() => {
    refresh && _onFinish();
  }, [refresh]);

  /** methods */
  const onChangeRegion = (regionItem, t) => {
    state.regionItem = regionItem;
    setState({
      regionItem,
    });

    t === 'search' && _onFinish(regionItem);
  };

  const _onFinish = async (regionItem) => {
    const value = _.get(regionItem, 'value', _.get(state, 'regionItem.value', ''));
    const params = {
      marketId: value,
    };
    onChange?.(params);
  };

  const _onReset = () => {
    // 重置&查询
    /* const dates = getDateRange();
    state.dates = dates;
    setState({
      dates,
    }); */
    onChangeRegion(power[0], 'search');
  };

  return (
    <Space size={16} wrap>
      <TjSelect
        style={{ width: 200 }}
        value={state.regionItem?.value}
        options={power}
        showSearch
        onChange={(v, opt) => onChangeRegion(opt)}
      />
      <Space size={16}>
        <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
          查询
        </Button>
        <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
          重置
        </Button>
      </Space>
    </Space>
  );
};
